﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WJP.Context;

namespace WJP.DataPortal
{
    internal class DataPortalFacade : IDataPortalServer
    {
        public DataPortalResult Fetch(Type objectType, object criteria, DataPortalContext context)
        {
            try
            {
                SetContext(context);
                return new FinalDataPortal().Fetch(objectType, criteria, context);
            }
            finally
            {
                ClearContext(context);
            }
        }

        public DataPortalResult Update(object obj, DataPortalContext context)
        {
            throw new NotImplementedException();
        }

        private static void SetContext(DataPortalContext context)
        {
            DistributionContext.SetClientContext(context.ClientContext);
            DistributionContext.SetGlobalContext(context.GlobalContext);
            Thread.CurrentThread.CurrentCulture = new CultureInfo(context.ClientCulture);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(context.ClientUICulture);
            //if (context.Principal == null)
            //    throw new SecurityException("Resources.BusinessPrincipalException Nothing")
            //    {
            //        Action = SecurityAction.Demand
            //    };
            //TODO:PlatformEnvironment.Principal = context.Principal;
        }

        private static void ClearContext(DataPortalContext context)
        {
            DistributionContext.Clear();
            //PlatformEnvironment.Principal = (IPrincipal)null;
        }
    }
}
